package com.changpei.common.exception;

import com.changpei.common.exception.custom.CustomException;
import com.changpei.common.result.Result;
import com.changpei.common.result.enums.CommonCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 *
 *
 * @author Way on 2021/7/18
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Result> exceptionHandler(HttpServletRequest request, Exception e) {
        Result result = Result.failed(CommonCode.SERVER_INTERNAL_ERROR, request.getRequestURI());
        recordErrorMessage(e);
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 自定义异常
     *
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<Result> notFoundExceptionHandler(HttpServletRequest request, CustomException e) {
        Result result = Result.failed(e.getCommonCode(), request.getRequestURI());
        recordErrorMessage(e);
        return new ResponseEntity<>(result, getHttpStatus(e.getCommonCode().code()));
    }

    /**
     * 根据系统自定义状态码获取httpStatus
     * @param code
     * @return
     */
    private HttpStatus getHttpStatus(int code) {
        String tmpCode = String.valueOf(code);
        // 取前三位，匹配http状态码，匹配不到统一返回系统内部错误的状态码
        int matchCode = Integer.parseInt(tmpCode.substring(0, 3));
        HttpStatus httpStatus = HttpStatus.resolve(matchCode);
        if (!ObjectUtils.isEmpty(httpStatus)) {
            return httpStatus;
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }

    /**
     * 记录详细错误信息
     * @param e
     */
    private void recordErrorMessage(Exception e) {
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter, true));
        log.error("当前错误信息，error : {}", stringWriter);
    }
}
